﻿@using Huirui.Cavan.Domain.MainBoundedContext.PurchaseModule
@model Huirui.Cavan.Presentation.ViewModel.PurchaseModule.IPurchaseOrderViewModel
@{
    Layout = null;
}
@using (Html.BeginForm(ActionConst.ADD, ControllerConst.PURCHASEORDER))
{
    var closeOrOpen = "关闭订单";
    if (Model.Item.Id.IsNotEmpty())
    {
        if (Model.Item.StockInStatus == PurchaseIdentifier.StockInStatus.Closed)
        {
            closeOrOpen = "打开订单";
        }
    }
    <div class="tool_bar">
        <input id="purch_save" type="submit" value="save" style="display: none;" />
        <input id="purch_reset" type="reset" style="display: none" />
        <input id="customer_query" type="submit" value="query" style="display: none;" />
        <a href="#" id="queryPurchaseOrder" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'" onclick="openWindow('mangePurchOrderWindow')">查询</a><a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-save'"
            onclick="javascript:$('#purch_save').click()">保存</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add',disabled:true" onclick="javascript:$('#purch_reset').click()">新增</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-copy',disabled:true">复制</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-delete',disabled:true">删除</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-buy',disabled:true">按子件采购</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-building',disabled:true">生成采购单</a>
        <a href="#" id="closeOrOpen" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-building'">
            @closeOrOpen</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-print',disabled:true">打印</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-collapse'" onclick="toggleHeard()">折叠/展开</a>
    </div>
    <table class="form_heard">
        <tr>
            <td class="c100">
                <label>订单日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.PurchaseDate, new { id = "purchaseDate", @Value = DateTime.Now.ToString("yyyy-MM-dd"), @class = "Wdate", @onfocus = "WdatePicker({wdate:true,isShowClear:false,readOnly:true,skin:'whyGreen',dateFmt:'yyyy-MM-dd',maxDate:'%y-%M-%d'})" })
            </td>
            <td class="c100">
                <label>采购人员:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.PurchaseEmployee.Id, new { id = "purchaseEmployeeCodeForPurchaseOrder" })
                @Html.HiddenFor(m => m.Item.PurchaseEmployee.Name, new { id = "purchaseEmployeeNameForPurchaseOrder" })
            </td>
            <td class="c100">
                <label>采购订单号:</label>
            </td>
            <td class="c164">
                @Html.TextBoxFor(m => m.Item.Id, new { id = "code" })
            </td>
            <td class="c100"></td>
            <td class="c160"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>供应商:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Supplier.Id, new { id = "supplierCodeForPurchaseOrder" })
            </td>
            <td colspan="2">
                @Html.TextBoxFor(m => m.Item.Supplier.Name, new { id = "supplierNameForPurchaseOrder" })
            </td>
            <td class="c100">
                <label>交货日期:</label>
            </td>
            <td class="c164">
                @Html.TextBoxFor(m => m.Item.DeliveryDate, new { id = "deliveryDate", @Value = DateTime.Now.ToString("yyyy-MM-dd"), @class = "Wdate", @onfocus = "WdatePicker({wdate:true,isShowClear:false,readOnly:true,skin:'whyGreen',minDate:'%y-%M-%d'})" })
            </td>
            <td class="c100">
                <label>审核状态:</label>
            </td>
            <td class="c160">
                <input type="text" />
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>币别:</label>
            </td>
            <td class="c160">
                @Html.DropDownList("currency", this.Model.Currencies, new { id = "currencyForPurchaseOrder" })
                @Html.HiddenFor(m => m.Item.Currency, new { id = "currencyValueForPurchaseOrder", value = "RMB"})
            </td>
            <td>
                <label>汇率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.CurrencyRate, new { id = "currencyRateForPurchaseOrder" })
            </td>
            <td class="c100">
                <label>税率:</label>
            </td>
            <td class="c164">
                @Html.TextBoxFor(m => m.TaxRate, new { id = "taxRateForPurchaseOrder" })
            </td>
            <td class="c100">
                @Html.Raw("%")
            </td>
            <td class="c160"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>仓库:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.WareHouse.Address, new { id = "wareHouseAddressForPurchaseOrder" })
                @Html.HiddenFor(m => m.Item.WareHouse.Id, new { id = "wareHouseCodeForPurchaseOrder" })
            </td>
            <td>
                <label>联系人:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Contact, new { id = "contact" })
            </td>
            <td class="c100">
                <label>电话:</label>
            </td>
            <td class="c164">
                @Html.TextBoxFor(m => m.Item.ContactTelephone, new { id = "contactTelephone" })
            </td>
            <td class="c100"></td>
            <td class="c160"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>送货地址:</label>
            </td>
            <td colspan="6">
                @Html.TextBoxFor(m => m.Item.DeliveryAddress, new { id = "address" })
            </td>
            <td class="c160">
                <a>请选择常用送货地址</a>
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>备注:</label>
            </td>
            <td colspan="6">
                @Html.TextBoxFor(m => m.Item.Remark, new { id = "remark" })
            </td>
            <td class="c160">
                <a>请选择常用备注</a>
            </td>
        </tr>
    </table>
    @Html.HiddenFor(m => m.PurchaseOrderDetails, new { id = "purchaseOrderDetails" })
}
<table id="selectedStocksForPurchaseOrder" title="存货列表" toolbar="#purch_order_tb">
</table>
<div id="purch_order_tb">
    <a href="#" id="selectStockForPurchaseOrder" class="easyui-linkbutton" iconcls="icon-checked" plain="true" onclick="InitSelectStock('stocksForPurchaseOrder');openWindow('selectStockWindowForPurchaseOrder')">选择商品</a>
</div>
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.STOCK, new { purpose = "ForPurchaseOrder" }); }
@{ Html.RenderAction(ActionConst.MANAGE, ControllerConst.PURCHASEORDER); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.SUPPLIER, new { purpose = "ForPurchaseOrder" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.WAREHOUSE, new { purpose = "ForPurchaseOrder" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.EMPLOYEE, new { purpose = "ForPurchaseOrder" }); }
<script type="text/javascript">
    $(function () {
        var lastIndex;
        var purchaseOrderDetails;
        $('#selectedStocksForPurchaseOrder').datagrid({
            columns: [[
                { field: 'NoPrefixId', title: '存货编码', width: 100 },
                { field: 'Id', title: '存货编码', width: 100, hidden: true },
                { field: 'Name', title: '存货名称', width: 80 },
                { field: 'Specification', title: '规格', width: 60 },
                { field: 'UnitTransfer', title: '计量单位', width: 80 },
                { field: 'Number', title: '数量', width: 100, editor: { type: 'text' } },
                { field: 'AssistantNumber', title: '辅助数量', width: 100 },
                { field: 'StandardPurchasePrice', title: '单价', width: 100 },
                { field: 'PurchaseAmount', title: '采购额', width: 80 },
                { field: 'LocalPurchaseAmount', title: '本币采购额', width: 80 },
                { field: 'TaxRate', title: '税率(%)', width: 80, editor: { type: 'text' } },
                { field: 'TaxAmount', title: '税额', width: 80 },
                { field: 'Cost', title: '成本额', width: 80 },
                { field: 'UnitCost', title: '单位成本', width: 80 },
                { field: 'Remark', title: '备注', width: 80 },
                { field: 'FromNumber', title: '', width: 80, hidden: true },
                { field: 'ToNumber', title: '', width: 80, hidden: true }
            ]]
        });

        $("#searchStockForPurchaseOrder").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#stocksForPurchaseOrder').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        var currentIndex;
        var currentRow;
        var rowId;
        var number;
        var taxRateForPurchaseOrder=0;
        var currencyRateForPurchaseOrder=1;

        $("#doSelectStockForPurchaseOrder").bind("click", function () {
            $('#selectedStocksForPurchaseOrder').datagrid('loadData', { total: 0, rows: [] });
            if (parseFloat($("#taxRateForPurchaseOrder").val()) > 0) {
                taxRateForPurchaseOrder = $("#taxRateForPurchaseOrder").val();
            }
            var rows = $('#stocksForPurchaseOrder').datagrid('getSelections');
            for (var i = 0; i < rows.length; i++) {
                insert(rows[i].NoPrefixId, rows[i].Id, rows[i].Name, rows[i].Specification, rows[i].UnitTransfer, 0, 0, rows[i].StandardPurchasePrice, 0, 0, taxRateForPurchaseOrder, 0, 0, 0, '', rows[i].FromNumber, rows[i].ToNumber);
            }
            closeWindow("selectStockWindowForPurchaseOrder");
        });

        function insert(noPrefixId, id, name, specification, unitTransfer, number, assistantNumber, standardPurchasePrice, purchaseAmount, localPurchaseAmount, taxRateForPurchaseOrder, taxAmount, cost, unitCost, remark, fromNumber, toNumber) {
            var rows = $('#selectedStocksForPurchaseOrder').datagrid('getRows');
            index = -1;
            if (rows.length == 0) {
                index = 0;
            }
            else {
                index = rows.length;
            }

            $('#selectedStocksForPurchaseOrder').datagrid('insertRow', {
                index: index,
                row: {
                    NoPrefixId: noPrefixId,
                    Id: id,
                    Name: name,
                    Specification: specification,
                    UnitTransfer:unitTransfer,
                    Number: number,
                    AssistantNumber: assistantNumber,
                    StandardPurchasePrice: standardPurchasePrice,
                    PurchaseAmount: purchaseAmount,
                    LocalPurchaseAmount: localPurchaseAmount,
                    TaxRate: taxRateForPurchaseOrder,
                    TaxAmount: taxAmount,
                    Cost: cost,
                    UnitCost: unitCost,
                    Remark: remark,
                    FromNumber: fromNumber,
                    ToNumber: toNumber,
                    DefaultCurrency: '@HuiruiProject.UserSettings.DefaultCurrency.Rate'
                }
            });
            $('#selectedStocksForPurchaseOrder').datagrid('selectRow', index);
            $('#selectedStocksForPurchaseOrder').datagrid('beginEdit', index);

            var ed = $('#selectedStocksForPurchaseOrder').datagrid('getEditors', index);
            for (var i = 0; i < ed.length; i++) {
                var e = ed[i];
                if (e.field == "Number") {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function () {
                        $('#selectedStocksForPurchaseOrder').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function () {
                        number = $(this).val();
                        if (parseFloat($("#currencyRateForPurchaseOrder").val()) > 0)
                        {
                            currencyRateForPurchaseOrder = $("#currencyRateForPurchaseOrder").val();
                        }
                        
                        currentIndex = $(this).attr("selectedStockRowIndex");
                        currentRow = $('#selectedStocksForPurchaseOrder').datagrid('getSelected');
                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "TaxRate") {
                                taxRateForPurchaseOrder = $(this).find("input").val();
                            }
                        });
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "PurchaseAmount") {
                                $(this).find("div").html(number * currentRow.StandardPurchasePrice);
                            }
                            if ($(this).attr("field") == "TaxAmount") {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardPurchasePrice) * (1 - (100 / (parseFloat(taxRateForPurchaseOrder) + 100)))).toFixed(2));
                            }
                            if ($(this).attr("field") == "Cost") {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardPurchasePrice) * (100 / (parseFloat(taxRateForPurchaseOrder) + 100))).toFixed(2));
                            }
                            if ($(this).attr("field") == "UnitCost") {
                                $(this).find("div").html(parseFloat(currentRow.StandardPurchasePrice * (100 / (parseFloat(taxRateForPurchaseOrder) + 100))).toFixed(2));
                            }
                            if ($(this).attr("field") == "AssistantNumber") {
                                $(this).find("div").html(parseFloat(currentRow.ToNumber * number / currentRow.FromNumber).toFixed(2));
                            }
                            if ($(this).attr("field") == "LocalPurchaseAmount") {
                                $(this).find("div").html(parseFloat(number * currentRow.StandardPurchasePrice * currentRow.DefaultCurrency / currencyRateForPurchaseOrder).toFixed(2));
                            }
                        });
                        $('#selectedStocksForPurchaseOrder').datagrid('unselectRow', currentIndex);
                        currentRow.Number = number;
                    })
                }
                else if (e.field == "TaxRate") {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function () {
                        $('#selectedStocksForPurchaseOrder').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function () {
                        taxRateForPurchaseOrder = $(this).val();
                        currentIndex = $(this).attr("selectedStockRowIndex");
                        currentRow = $('#selectedStocksForPurchaseOrder').datagrid('getSelected');
                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "Number") {
                                number = $(this).find("input").val();
                            }
                            if ($(this).attr("field") == "TaxAmount") {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardPurchasePrice) * (1 - (100 / (parseFloat(taxRateForPurchaseOrder) + 100)))).toFixed(2));
                            }
                        });
                        $('#selectedStocksForPurchaseOrder').datagrid('unselectRow', currentIndex);
                        currentRow.TaxRate = taxRateForPurchaseOrder;
                    })
                }
            }
        }

        $("form[action^='/purchaseorder/add']").submit(function () {
            var rows = $('#selectedStocksForPurchaseOrder').datagrid('getRows');
            purchaseOrderDetails = "[";
            for (var i = 0; i < rows.length; i++) {
                if (i == (rows.length - 1)) {
                    purchaseOrderDetails = purchaseOrderDetails + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"TaxRate\" :" + rows[i].TaxRate + " }";
                }
                else {
                    purchaseOrderDetails = purchaseOrderDetails + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"TaxRate\" :" + rows[i].TaxRate + " }" + ",";
                }
            }
            purchaseOrderDetails = purchaseOrderDetails + "]";
            $("#purchaseOrderDetails").val(purchaseOrderDetails);
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (data) {
                    if (data.IsSuccess) {
                        alert(data.Messages[0]);
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#closeOrOpen").bind("click", function () {
            var url = '/purchaseorder';
            if ($(this).val() == '关闭订单') {
                url = url + '/close/' + $("#code").val();
            }
            else {
                url = url + '/open/' + $("#code").val();
            }
            $.ajax({
                url: url,
                type: 'Post',
                success: function (data) {
                    if (data.IsSuccess) {
                        alert(data.Messages[0]);
                        if ($("#closeOrOpen").val() == '关闭订单') {
                            $("#closeOrOpen").val('打开订单')
                        }
                        else {
                            $("#closeOrOpen").val('关闭订单')
                        }
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })
        });

        $("form[action^='/purchaseorder/list']").submit(function () {
            var stockInStatues = '';
            var checkedStatues = ''
            $("input[type='checkbox'][name='stockInStatus']:checked").each(function () {
                stockInStatues = stockInStatues + $(this).val() + ",";
            });
            $("#stockInStatues").val(stockInStatues);
            $("input[type='checkbox'][name='checkedStatus']:checked").each(function () {
                checkedStatues = checkedStatues + $(this).val() + ",";
            });
            $("#checkedStatues").val(checkedStatues);
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#purchaseOrders').datagrid({
                            toolbar: '#purch_order_manage_tb',
                            columns: [[
                                {
                                    field: 'Code', title: '采购订单编号', width: 60,
                                    formatter: function (value, row, index) {
                                        var e = '<a href="#" onclick="addTab(\'采购订单\', \'/purchaseorder/add/' + value + '\');closeWindow(\'mangePurchOrderWindow\')">' + value + '</a> ';
                                        return e;
                                    }
                                },
                                { field: 'PurchaseDate', title: '日期', width: 100 },
                                { field: 'SupplierName', title: '供应商', width: 80, align: 'right' },
                                { field: 'SupplierInvoiceNumber', title: '供应商发票号', width: 80, align: 'center' },
                                { field: 'PurchaseEmployeeCode', title: '采购人员', width: 60 },
                                { field: 'WareHouseName', title: '地点', width: 100 },
                                { field: 'Currency', title: '币别', width: 80, align: 'right' },
                                { field: 'Amount', title: '金额', width: 80, align: 'center' },
                                { field: 'DeliveryDate', title: '交货日期', width: 60 },
                                { field: 'CheckedStatus', title: '审核状态', width: 100 },
                                { field: 'StockInStatus', title: '入库状态', width: 80, align: 'right' }
                            ]],
                            data: result
                        });
                    }
                    else {
                        $('#purchaseOrders').datagrid('loadData', { total: 0, rows: [] });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#supplierCodeForPurchaseOrder").bind("click", function () {
            InitSelectSupplier('suppliersForPurchaseOrder');
            openWindow("selectSupplierWindowForPurchaseOrder");
        });

        $("#searchSupplierForPurchaseOrder").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#suppliersForPurchaseOrder').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectSupplierForPurchaseOrder").bind("click", function () {
            var currentRow = $('#suppliersForPurchaseOrder').datagrid('getSelected');
            $("#supplierCodeForPurchaseOrder").val(currentRow.Id);
            $("#supplierNameForPurchaseOrder").val(currentRow.Name);
            closeWindow("selectSupplierWindowForPurchaseOrder");
        });

        $("#wareHouseAddressForPurchaseOrder").bind("click", function () {
            InitSelectWareHouse('wareHousesForPurchaseOrder');
            openWindow("selectWareHouseWindowForPurchaseOrder");
        });

        $("#searchWareHouseForPurchaseOrder").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#wareHousesForPurchaseOrder').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectWareHouseForPurchaseOrder").bind("click", function () {
            var currentRow = $('#wareHousesForPurchaseOrder').datagrid('getSelected');
            $("#wareHouseCodeForPurchaseOrder").val(currentRow.Id);
            $("#wareHouseAddressForPurchaseOrder").val(currentRow.Address);
            closeWindow("selectWareHouseWindowForPurchaseOrder");
        });

        $("#purchaseEmployeeCodeForPurchaseOrder").bind("click", function () {
            InitSelectEmployee('employeesForPurchaseOrder');
            openWindow("selectEmployeeWindowForPurchaseOrder");
        });

        $("#searchEmployeeForPurchaseOrder").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#employeesForPurchaseOrder').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectEmployeeForPurchaseOrder").bind("click", function () {
            var currentRow = $('#employeesForPurchaseOrder').datagrid('getSelected');
            $("#purchaseEmployeeCodeForPurchaseOrder").val(currentRow.Id);
            $("#purchaseEmployeeNameForPurchaseOrder").val(currentRow.Name);
            closeWindow("selectEmployeeWindowForPurchaseOrder");
        });

        $("select#currencyForPurchaseOrder").bind("change", function () {
            $("#currencyValueForPurchaseOrder").val($(this).find("option:selected").text());
            $("#currencyRateForPurchaseOrder").val($(this).val());
        });
    });
</script>
